package com.changgou.search.searchService.searchServiceImpl;

import com.alibaba.fastjson.JSON;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.searchService.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @version v1.0
 * @ProjectName: changgou_parent
 * @ClassName: SearchServiceImpl
 * @Description: TODO(es搜索功能接口)
 * @Author: Xu Fj
 * @Date: 2020/3/1 14:50
 */
@Service
public class SearchServiceImpl implements SearchService {
    @Autowired //注入es操作对象
    private ElasticsearchTemplate elasticsearchTemplate;

    //定义搜索到的结果展示20页,提升页面加载效率
    public static final Integer PAGE_SIZE = 20;

    @Override
    public Map search(Map<String, String> paramMap) throws Exception {
        HashMap<String, Object> resultMap = new HashMap<>();

        if (null != paramMap){
            //多条件查询对象,用来封装过个查询条件
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            //如果包含key值为keywords的查询条件
            if (!StringUtils.isEmpty(paramMap.get("keywords"))){
                //组合查询条件,match分词查询
                boolQueryBuilder.must(QueryBuilders.matchQuery("name",paramMap.get("keywords")).operator(Operator.AND));
            }

            if (!StringUtils.isEmpty(paramMap.get("brand"))){
                //termQuery精确查询,并不会分词
                boolQueryBuilder.filter(QueryBuilders.termQuery("brandName",paramMap.get("brand")));
            }

            //条件构建对象
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);

            //品牌聚合查询(分组)
            String skuBrand = "skuBrand";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));

            //规格聚合查询(分组)
            String skuSpec = "skuSpec";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));

            //按照相关字段进行排序查询
            // 1.当前域 2.当前的排序操作(升序ASC,降序DESC)
            if (StringUtils.isNotEmpty(paramMap.get("sortField")) && StringUtils.isNotEmpty(paramMap.get("sortRule"))){
                if ("ASC".equals(paramMap.get("sortRule"))){
                    //升序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort((paramMap.get("sortField"))).order(SortOrder.ASC));
                }else{
                    //降序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort((paramMap.get("sortField"))).order(SortOrder.DESC));
                }
            }

            //设置高亮域以及高亮的样式
            HighlightBuilder.Field field = new HighlightBuilder.Field("name")//高亮域
                    .preTags("<span style='color:red'>")//高亮样式的前缀
                    .postTags("</span>");//高亮样式的后缀
            nativeSearchQueryBuilder.withHighlightFields(field);

            //开启分页查询
            String pageNum = paramMap.get("pageNum");
            String pageSize = paramMap.get("pageSize");

            if (pageNum == null){
                pageNum = "1";
            }
            if (pageSize == null){
                pageSize = "30";
            }
            //设置分页
            nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum)-1,Integer.parseInt(pageSize)));


            //按照规格进行过滤查询
            for (String key : paramMap.keySet()) {
                if(key.startsWith("spec_")){
                    String value = paramMap.get(key).replace("%2B", "+");

                    boolQueryBuilder.filter(QueryBuilders.termQuery("specMap."+key.substring(5)+".keyword",value));
                }
            }

            //按价格查询
            if (StringUtils.isNotEmpty(paramMap.get("price"))){
                String[] prices = paramMap.get("price").split("-");
                if (prices.length == 2){
                    boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(prices[1]));
                }
                boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));
            }
            
            //执行查询,返回结果对象
            AggregatedPage<SkuInfo> aggregatedPage = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    ArrayList list = new ArrayList();
                    SearchHits hits = searchResponse.getHits();
                    if (hits != null) {
                        for (SearchHit hit : hits) {
                            SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
                            list.add((T) skuInfo);
                        }
                    }
                    return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                }
            });
            //总条数
            resultMap.put("total",aggregatedPage.getTotalElements());
            //总页数
            resultMap.put("totalPages",aggregatedPage.getTotalPages());
            //查询结果集合
            resultMap.put("rows",aggregatedPage.getContent());
            //封装品牌的分组查询结果
            StringTerms brandTerms = (StringTerms) aggregatedPage.getAggregation(skuBrand);
            List<String> list = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("brandList",list);

            //封装按规格分组查询的结果
            StringTerms specTerms = (StringTerms) aggregatedPage.getAggregation(skuSpec);
            List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("specList",this.formatSpec(specList));

            //封装当前页
            resultMap.put("pageNum",pageNum);
            return resultMap;

        }
        return null;
    }





    /**
     * @Description: TODO(规格数据格式转换)
     */
    public Map<String, Set<String>> formatSpec(List<String> specList){
        HashMap<String, Set<String>> resultMap = new HashMap<>();
        if (specList!=null&&specList.size()>0){
            //遍历得到每个规格数据的JSON串
            for (String specJsonString : specList) {
                Map<String,String> specMap = JSON.parseObject(specJsonString, Map.class);
                for (String specKey : specMap.keySet()) {
                    Set<String> specSet = resultMap.get(specKey);
                    if (specSet == null){
                        specSet = new HashSet<>();
                    }

                    specSet.add(specMap.get(specKey));
                    resultMap.put(specKey,specSet);
                }
            }
        }
        return resultMap;
    }
}
